<template>
    <div id="app" class=" min-h-screen bg-gray-50 font-sans" v-if="post">
        <!-- 顶部导航 -->
        <header class="relative top-0 bg-white shadow-sm" style="z-index:51;">
            <div class="container mx-auto px-4 py-4 flex items-center justify-between">
                <button class="text-gray-700 hover:text-pink-500 transition-colors" @click="toUrl('/app')">
                    <i class="fa fa-arrow-left text-xl"></i>
                </button>
                <!-- <h1 class="text-lg font-medium text-gray-800" v-if="post.coverTitle">{{ post.coverTitle }}</h1> -->
                <h1 class="text-lg font-medium text-gray-800">{{ post.title }}</h1>
                <div class="w-6"> <!-- 分享按钮 -->
                    <button class="hover:text-primary transition-colors" @click="sharePost">
                        <i class="fa fa-share-alt"></i>
                    </button>
                </div>
            </div>
        </header>



        <!-- 文章主体 -->
        <main class="container mx-auto px-4">

            <!-- 封面图 -->
            <!-- <div
                class="relative w-full rounded-xl overflow-hidden mb-6 shadow-md transform transition-transform hover:scale-[1.01]"> -->
            <!-- <img :src="baseApi + post.image" alt="" class="w-full h-auto object-cover"> -->
            <!-- </div> -->

            <!-- 文章标题 -->
            <!-- <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-gray-900 leading-tight mb-4">
                {{ post.title }}
            </h1> -->

            <!-- 文章标签 -->
            <div class="flex flex-wrap gap-2">
                <span class="px-3 py-1 bg-pink-100 text-pink-700 rounded-full text-sm font-medium"
                    v-for="value in post.tagTitle">
                    {{ value }}
                </span>
                <!-- <span class="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm font-medium">
                    肌肤修护
                </span>
                <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-sm font-medium">
                    抗衰保养
                </span>
                <span class="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-sm font-medium">
                    科学护肤
                </span> -->
            </div>

            <!-- 文章内容 -->
            <article class="text-gray-700 leading-relaxed mb-12 space-y-6">
                <div class="content-center">
                    <div class="" v-html="post.content">
                    </div>
                </div>
            </article>
            <ProductQuote v-if="type == 'app'" :product="productInfo" :preferredArea="preferredArea"
                :isQuoteVisible="true" :isFloating="false" :isBuy="false" :countdownTime="countdownConfig"
                :productItems="productItems" style="margin:35px 0" />
            <!-- 评论区 -->
            <Comment :post-id="id" :post-type="type" class="mb-16" />

        </main>

        <!-- 底部按钮 -->
        <footer v-if="type == 'app'"
            class="sticky bottom-0 left-0 right-0 bg-white border-t border-gray-200 py-4 px-6 shadow-lg z-20">
            <button @click="clickShowModal()"
                class="w-full bg-gradient-to-r from-pink-500 to-pink-600 text-white font-medium py-3 px-6 rounded-full shadow-md hover:shadow-lg transform hover:-translate-y-0.5 transition-all focus:outline-none focus:ring-2 focus:ring-pink-400 focus:ring-opacity-50">
                点击测试我的专属方案
            </button>
        </footer>

        <!-- exam组件弹窗 -->
        <el-dialog :visible.sync="showExam" width="60%" :show-close="false" :modal-append-to-body="false" center
            custom-class="beauty-dialog" class="unsetStyle">
            <div class="exam-popup-content bg-white rounded-xl overflow-hidden shadow-xl">
                <div class="bg-gradient-to-r from-primary to-secondary py-4 px-6">
                    <h2 class="text-xl font-semibold text-white text-center"></h2>
                </div>
                <div style="text-align: center;font-size: 14px;">🎯（饮食 · 运动 · 护肤 · 习惯 · 每日建议，全为你定制）</div>
                <exam style="width:100%;height: 60vh;" :data="examData" title="30秒测出你的专属美容方案！"
                    @reExamClose="handleExamClose" subText="✅ 精准匹配我的方案 →" />

            </div>
        </el-dialog>

        <!-- 年龄选择弹窗 -->
        <div v-if="showModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
            @click="showModal = false">
            <div class="bg-white rounded-2xl p-6 w-full max-w-md shadow-2xl transform transition-all" @click.stop>
                <!-- 弹窗标题 -->
                <h3 class="text-xl font-bold text-gray-800 mb-6 flex items-start">
                    <span class="text-2xl mr-2">📝</span>
                    <span>选你的年龄区间<br><span class="text-sm font-normal text-gray-500">(点击选项即可提交)</span></span>
                </h3>

                <!-- 年龄选项 -->
                <div class="space-y-3 mb-6">
                    <label v-for="(age, index) in ageOptions" :key="index"
                        class="flex items-center p-4 border border-gray-200 rounded-xl cursor-pointer hover:bg-pink-50 hover:border-pink-200 transition-colors">
                        <input type="radio" name="ageGroup" :value="age.value" v-model="selectedAge"
                            class="w-5 h-5 text-pink-500 focus:ring-pink-400 border-gray-300">
                        <span class="ml-3 text-gray-700">{{ age.label }}</span>
                    </label>
                </div>

                <!-- 提交按钮 -->
                <button @click="submitAge" :disabled="!selectedAge"
                    class="w-full py-3 px-4 bg-pink-500 text-white font-medium rounded-xl shadow hover:bg-pink-600 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed">
                    去查看专属方案
                </button>
            </div>
        </div>

        <!-- 结果提示弹窗 -->
        <div v-if="showResult" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
            @click="showResult = false">
            <div class="bg-white rounded-2xl p-6 w-full max-w-md shadow-2xl transform transition-all" @click.stop>
                <div class="text-center mb-4">
                    <div
                        class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 text-green-500 mb-4">
                        <i class="fa fa-check text-2xl"></i>
                    </div>
                    <h3 class="text-xl font-bold text-gray-800 mb-2">提交成功！</h3>
                    <p class="text-gray-600">已为您准备专属方案和优惠</p>
                </div>

                <div class="bg-gray-50 p-4 rounded-xl mb-6">
                    <h4 class="font-medium text-gray-800 mb-2">您的专属内容：</h4>
                    <p class="text-gray-700 mb-3">{{ collagenTips }}</p>
                    <div class="flex items-center p-3 bg-pink-50 rounded-lg">
                        <i class="fa fa-ticket text-pink-500 mr-2"></i>
                        <span class="text-gray-800 font-medium">品牌150元专属优惠券</span>
                    </div>
                </div>

                <button @click="showResult = false"
                    class="w-full py-3 px-4 bg-pink-500 text-white font-medium rounded-xl shadow hover:bg-pink-600 transition-colors">
                    关闭
                </button>
            </div>
        </div>

        <!-- 分享弹窗 -->
        <div v-if="showShareModal"
            class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4"
            @click="showShareModal = false">
            <div class="bg-white rounded-2xl p-6 w-full max-w-md shadow-2xl transform transition-all" @click.stop>
                <div class="flex justify-between items-center mb-6">
                    <h3 class="text-xl font-bold text-gray-800">分享文章</h3>
                    <button @click="showShareModal = false" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times"></i>
                    </button>
                </div>

                <div class="grid grid-cols-4 gap-4 mb-6">
                    <div class="flex flex-col items-center">
                        <button
                            class="w-16 h-16 rounded-full bg-green-500 flex items-center justify-center text-white mb-2">
                            <i class="fa fa-wechat text-2xl"></i>
                        </button>
                        <span class="text-sm text-gray-600">微信</span>
                    </div>
                    <div class="flex flex-col items-center">
                        <button
                            class="w-16 h-16 rounded-full bg-blue-500 flex items-center justify-center text-white mb-2">
                            <i class="fa fa-qq text-2xl"></i>
                        </button>
                        <span class="text-sm text-gray-600">QQ</span>
                    </div>
                    <div class="flex flex-col items-center">
                        <button
                            class="w-16 h-16 rounded-full bg-red-500 flex items-center justify-center text-white mb-2">
                            <i class="fa fa-weibo text-2xl"></i>
                        </button>
                        <span class="text-sm text-gray-600">微博</span>
                    </div>
                    <div class="flex flex-col items-center">
                        <button
                            class="w-16 h-16 rounded-full bg-gray-500 flex items-center justify-center text-white mb-2">
                            <i class="fa fa-link text-2xl"></i>
                        </button>
                        <span class="text-sm text-gray-600">复制链接</span>
                    </div>
                </div>

                <button @click="showShareModal = false"
                    class="w-full py-3 px-4 bg-gray-200 text-gray-800 font-medium rounded-xl hover:bg-gray-300 transition-colors">
                    取消
                </button>
            </div>
        </div>
    </div>
</template>

<script>
import { mapGetters } from "vuex";

import { listLabel } from "@/api/demo/label";
import { listCover, getCover, delCover, addCover, updateCover } from "@/api/demo/cover";
import { listLibrary, getLibrary, delLibrary, addLibrary, updateLibrary } from "@/api/demo/library";
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/demo/article";
import { listCustomer, getCustomerByOpenId, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/demo/customer";
import { listComboByArticleId } from "@/api/demo/combo";


import ProductQuote from '../components/ProductQuote.vue'


import Comment from '@/views/components/Comment.vue';

export default {
    ...mapGetters(["user"]),

    components: {
        Comment,
        ProductQuote
    },
    data() {
        return {
            showExam: false,
            examData: [],
            examTitle: "",

            CustomerInfo: null,
            baseApi: process.env.VUE_APP_BASE_API,
            labelList: [],

            showModal: false,
            showResult: false,
            showShareModal: false,
            selectedAge: null,
            ageOptions: [
                { label: '20-25岁', value: '20-25' },
                { label: '26-30岁', value: '26-30' },
                { label: '31-35岁', value: '31-35' },
                { label: '35+岁', value: '35+' }
            ],
            collagenTips: '',
            post: null,
            id: 0,
            type: 'app',



            // 1. 套装基本信息
            productInfo: {
                // name: '焕颜保湿护肤套装',
                // description: '包含洁面乳、精华液、保湿霜和面膜，专为敏感肌肤设计，深层滋养，焕发肌肤活力',
                // image: require('@/assets/images/mr/bann/banner (4).jpg'), // 主图
                // originalPrice: 1299, // 原价
                // currentPrice: 699,   // 现价
                // stock: 15,           // 剩余库存
                // gifts: ['化妆棉1包', '小样套装', '专属化妆包'] // 赠品
            },

            // 2. 优惠地区
            preferredArea: '小店区',

            // 3. 倒计时配置（初始时间）
            countdownConfig: {
                days: 1,    // 天
                hours: 12,  // 时
                minutes: 30,// 分
                seconds: 45 // 秒
            },

            // 4. 产品列表（套装包含的单品）
            productItems: [
                // {
                //     id: 1,
                //     name: '氨基酸温和洁面乳',
                //     specs: '100ml / 深层清洁 / 温和不刺激',
                //     price: 199,
                //     image: 'https://picsum.photos/100/100?random=11'
                // },
                // {
                //     id: 2,
                //     name: '玻尿酸保湿精华液',
                //     specs: '30ml / 补水锁水 / 提亮肤色',
                //     price: 329,
                //     image: 'https://picsum.photos/100/100?random=12'
                // },
                // {
                //     id: 3,
                //     name: '修护保湿霜',
                //     specs: '50g / 锁水保湿 / 修护屏障',
                //     price: 269,
                //     image: 'https://picsum.photos/100/100?random=13'
                // },
                // {
                //     id: 4,
                //     name: '焕颜修护面膜（5片装）',
                //     specs: '补水滋养 / 舒缓修护',
                //     price: 199,
                //     image: 'https://picsum.photos/100/100?random=14'
                // }
            ],
        };
    },
    created() {
        this.id = this.$route.query.id;
        localStorage.setItem('postId', this.id);
        this.type = this.$route.query.type;
        this.init();
    },
    mounted() {

    },

    methods: {

        async init() {
            this.CustomerInfo = JSON.parse(localStorage.getItem('CustomerInfo'));
            if (this.CustomerInfo == null) {
                this.CustomerInfo = { openId: '000', deptId: '100', age: '' };
            }
            console.log("CustomerInfo", this.CustomerInfo);
            await this.getLabelList();

            if (this.type == 'app') {
                this.getApp();
                this.getCombo();
                this.startExam();
            } else if (this.type == 'case') {
                this.getCase();
            } else if (this.type == 'article') {
                this.getWen();
            }
        },
        async getLabelList() {
            await listLabel({ pageNum: 1, pageSize: 1000 }).then(response => {
                this.labelList = response.rows;
            });
        },
        startExam() {

            listTopicForTask({
                taskId: this.taskId,
                questionStatus: 1,
            }).then(res => {
                console.log(res)
                if (res.code == 200) {
                    if (res.data.length) {

                        this.examData = res.data
                        this.examTitle = "用户偏好测试"
                        // this.$refs.popupDiv.open("bottom")
                        // this.closeScanPopup()
                    } else {
                        // uni.showToast({
                        //   icon: 'none',
                        //   title: "无对应测试题"
                        // })
                    }
                } else {
                    // uni.showToast({
                    //   icon: 'none',
                    //   title: "题库错误"
                    // })
                }
            })

        },
        getCase() {
            getLibrary(this.id).then(res => {
                if (res.code == 200) {
                    res.data.image = res.data.imageUrl;
                    res.data.tagTitle = (res.data.tags) ? this.getTagTitle(res.data.tags.split(',')) : [];
                    this.post = res.data;
                    console.log(this.post);
                }
            });
        },
        getWen() {
            getArticle(this.id).then(res => {
                if (res.code == 200) {
                    this.post = res.data;
                }
            });
        },
        getApp() {
            getCover(this.id).then(res => {
                if (res.code == 200) {
                    this.post = res.data;
                }
            });
        },
        getCombo() {
            listComboByArticleId(localStorage.getItem("postId")).then(res => {
                if (res.code == 200) {
                    let data = res.data;

                    // 根据返回数据填充productInfo
                    this.productInfo = {
                        name: data.name,
                        description: data.introduction,
                        image: this.baseApi + data.image,
                        // originalPrice: data.price,
                        currentPrice: data.price,
                        stock: data.num,
                        gifts: data.freeGiftList ? data.freeGiftList.map(gift => gift.product.name) : [],
                    };

                    // // 根据返回数据填充productItems
                    this.productItems = data.productList ? data.productList.map(item => ({
                        id: item.product.id,
                        name: item.product.name,
                        specs: item.product.specification,
                        price: item.product.price,
                        image: this.baseApi + item.product.image, // 数据中未提供图片字段
                        num: item.num
                    })) : [];

                }
            });
        },
        sharePost() {
            // 打开分享弹窗
            this.showShareModal = true;
        },
        toUrl(url) {
            this.$router.push(url);
        },
        clickShowModal() {
            if (this.CustomerInfo && this.CustomerInfo.age) {
                this.showModal = false;
                this.$router.push('/mr/guwen');
            } else {
                this.showModal = true
            }
        },
        submitAge() {
            console.log(this.CustomerInfo);
            this.CustomerInfo.age = this.selectedAge;
            updateCustomer({
                id: this.CustomerInfo.id,
                age: this.CustomerInfo.age,
            }).then(res => {
                if (res.code == 200) {
                    localStorage.setItem('CustomerInfo', JSON.stringify(this.CustomerInfo));
                    this.showModal = false;
                    this.$router.push('/mr/guwen');
                }
            });

            return
            if (!this.selectedAge) return;

            // 根据年龄设置对应的胶原修护重点
            switch (this.selectedAge) {
                case '20-25':
                    this.collagenTips = '20-25岁胶原修护重点：预防为主，注重保湿和防晒，避免胶原蛋白过早流失，可适当补充基础胶原蛋白肽。';
                    break;
                case '26-30':
                    this.collagenTips = '26-30岁胶原修护重点：加强内源性胶原蛋白合成，使用含维生素C、肽类成分的产品，配合规律作息。';
                    break;
                case '31-35':
                    this.collagenTips = '31-35岁胶原修护重点：刺激胶原蛋白再生，可尝试含视黄醇、玻色因等成分的抗衰产品，结合适度运动。';
                    break;
                case '35+':
                    this.collagenTips = '35+岁胶原修护重点：综合修护方案，内外结合补充，选择具有多重抗衰成分的产品，注重整体肌肤健康。';
                    break;
            }

            this.showModal = false;
            this.showResult = true;
        },
        getTagTitle(tags) {
            console.log(tags);
            let tagTitle = [];
            for (let i = 0; i < tags.length; i++) {

                for (let j = 0; j < this.labelList.length; j++) {
                    console.log(tags[i], this.labelList[j].id);
                    if (tags[i] == this.labelList[j].id) {
                        tagTitle.push(this.labelList[j].label);
                        break;
                    }
                }
            }
            return tagTitle
        }
    }
};
</script>

<style scoped>
@media (min-width: 1500px) {
    #app {
        max-width: 1000px;
        margin: 0 auto;
    }

    .content-center {
        width: 700px;
    }
}

/* 基础样式补充 */
input[type="radio"]:checked+span {
    color: #ca7599;
    font-weight: 500;
}

input[type="radio"]:checked {
    accent-color: #ca7599;
}

.content-center img {
    margin: 0 auto;
    display: block;
}
</style>